﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Utilities;

//using SPaDevToolkit.Administration.UI;

using Northwind.ServiceObjects;
using Northwind.ServiceObjects.AdminUI;

namespace Northwind.ServiceApplication.AdminUI
{
    public partial class CreateNorthwindApplication : ServiceApplicationAdminPage   // SPaWebServiceApplicationAdminPage<NorthwindApplication, NorthwindService>
    {
        private SPDatabaseParameters m_northwindDatabaseParameters;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.PageMode == PageEditMode.Create)
            {
                this.litPageTitle.Text = "Create a New Northwind Application";
            }
            else
            {
                this.litPageTitle.Text = "Edit the Northwind Application";
            }
            if (!this.Page.IsPostBack)
            {
                this.InitializeUIControls();
            }
        }

        protected void ValidateNorthwindDatabase(object sender, ServerValidateEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            this.m_northwindDatabaseParameters = SPDatabaseParameters.CreateParameters(((ContentDatabaseSection)this.dbSection_Northwind).DatabaseName, ((ContentDatabaseSection)this.dbSection_Northwind).DatabaseServer, ((ContentDatabaseSection)this.dbSection_Northwind).UseWindowsAuthentication ? null : ((ContentDatabaseSection)this.dbSection_Northwind).DatabaseUserName, ((ContentDatabaseSection)this.dbSection_Northwind).UseWindowsAuthentication ? null : ((ContentDatabaseSection)this.dbSection_Northwind).DatabasePassword, ((ContentDatabaseSection)this.dbSection_Northwind).FailoverDatabaseServer, SPDatabaseParameterOptions.None);
            if (this.PageMode == PageEditMode.Create)
            {
                this.m_northwindDatabaseParameters.Validate(SPDatabaseValidation.CreateNew);
            }
            else if (DatabaseCredentialsChanged(this.m_northwindDatabaseParameters, ServiceApplication.NorthwindDatabase))
            {
                this.m_northwindDatabaseParameters.Validate(SPDatabaseValidation.AttachExisting);
            }
            else
            {
                this.m_northwindDatabaseParameters = null;
            }
        }




        private static bool DatabaseCredentialsChanged(SPDatabaseParameters parameters, SPDatabase database)
        {
            return ((parameters.Username != database.Username) || (((parameters.Username != null) && !string.IsNullOrEmpty(parameters.Password)) && (parameters.Password != database.Password)));
        }



        protected override void OnCreateApplication()
        {
            NorthwindApplication serviceApplication = null;
            NorthwindApplicationProxy serviceApplicationProxy = null;

            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.Begin();

                try
                {
                    string name = txtBoxServiceName.Text.Trim();
                    SPIisWebServiceApplicationPool orCreateApplicationPool = ((IisWebServiceApplicationPoolSection)appPoolSection).GetOrCreateApplicationPool();

                    serviceApplication = NorthwindApplication.Create(name, NorthwindService.Local, orCreateApplicationPool, m_northwindDatabaseParameters);

                    if (serviceApplication == null)
                        throw new NullReferenceException("NorthwindApplication");

                    serviceApplication.Update(true);
                    serviceApplication.Provision();

                    serviceApplicationProxy = (NorthwindApplicationProxy)NorthwindService.Local.CreateProxy(name, serviceApplication, null);

                    if (serviceApplicationProxy == null)
                        throw new NullReferenceException("NorthwindApplicationProxy");

                    serviceApplicationProxy.Update(true);
                    if (this.defaultProxyGroupDropDown.Enabled && (this.defaultProxyGroupDropDown.SelectedIndex == 0))
                    {
                        SPServiceApplicationProxyGroup group = SPServiceApplicationProxyGroup.Default;
                        group.Add(serviceApplicationProxy);
                        group.Update();
                    }

                    serviceApplicationProxy.Provision();


                    operation.EndScript("window.frameElement.commitPopup();");
                }
                catch (Exception ex)
                {
                    if (serviceApplicationProxy != null)
                    {
                        serviceApplicationProxy.Unprovision();
                        serviceApplicationProxy.Delete();
                    }

                    if (serviceApplication != null)
                    {
                        serviceApplication.Unprovision();
                        serviceApplication.Delete();
                    }

                    throw new SPException("Failed to create Northwind Service Application", ex);
                }
            }
        }

        protected override void OnUpdateApplication()
        {
            SPFarm.Local.Services.GetValue<NorthwindService>();
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = "Please wait while the service application is updated";
                operation.Begin();
                try
                {
                    string text = this.txtBoxServiceName.Text;
                    SPIisWebServiceApplicationPool orCreateApplicationPool = ((IisWebServiceApplicationPoolSection)this.appPoolSection).GetOrCreateApplicationPool();
                    ServiceApplication.Update(text, orCreateApplicationPool, this.m_northwindDatabaseParameters);
                    operation.EndScript("window.frameElement.commitPopup();");
                }
                catch (Exception ex)
                {
                    throw new SPException("Failed to update Northwind Service Application", ex);
                }
            }
        }

        private void InitializeUIControls()
        {
            this.ShowHideDefaultProxyGroupDropDown();
            if (this.PageMode == PageEditMode.Create)
            {
                ((DialogMaster)this.Page.Master).OkButton.Text = "Create";
                ((ContentDatabaseSection)this.dbSection_Northwind).DatabaseName = "NorthwindDB";
                ((ContentDatabaseSection)this.dbSection_Northwind).Description = "Create a new Northwind service application";
            }
            else
            {
                NorthwindApplication northwindApplication = this.ServiceApplication;
                this.txtBoxServiceName.Text = northwindApplication.Name;
                ((IisWebServiceApplicationPoolSection)this.appPoolSection).SetSelectedApplicationPool(northwindApplication.ApplicationPool);
                ((ContentDatabaseSection)this.dbSection_Northwind).ConnectionString = northwindApplication.NorthwindDatabase.DatabaseConnectionString;
                ((ContentDatabaseSection)this.dbSection_Northwind).DisplayMode = ContentDatabaseSectionMode.AuthenticationEdit;
                proxyGroupSection.Visible = false;
            }
        }

        private void ShowHideDefaultProxyGroupDropDown()
        {
            this.defaultProxyGroupDropDown.Enabled = false;
            if (SPServiceApplicationProxyGroup.Default.Proxies.GetEnumerator().Current == null)
            {
                this.defaultProxyGroupDropDown.Enabled = true;
                this.defaultProxyGroupDropDown.SelectedIndex = 0;
            }
        }

    }
}
